package com.shujia.hbase.api;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;

import java.io.IOException;

public class Demo6HdfsToHbase {


    public static class HdfsToHbaseMap extends Mapper<LongWritable, Text, Text, NullWritable> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

            context.write(value, NullWritable.get());
        }
    }

    public static class HdfsToHbaseReduce extends TableReducer<Text, NullWritable, NullWritable> {
        @Override
        protected void reduce(Text key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {

            String line = key.toString();

            String[] split = line.split(",");
            String id = split[0];
            String name = split[1];
            String age = split[2];
            String gender = split[3];
            String clazz = split[4];


            //构建put对象

            Put put = new Put(id.getBytes());
            put.add("info".getBytes(), "name".getBytes(), name.getBytes());
            put.add("info".getBytes(), "age".getBytes(), age.getBytes());
            put.add("info".getBytes(), "gender".getBytes(), gender.getBytes());
            put.add("info".getBytes(), "clazz".getBytes(), clazz.getBytes());


            //将数据写入hbase
            context.write(NullWritable.get(), put);


        }
    }

    public static void main(String[] args) throws Exception {


        Configuration conf = new Configuration();

        //指定zk连接地址
        conf.set("hbase.zookeeper.quorum", "node1:2181,node2:2181,node3:2181");


        Job job = Job.getInstance(conf);

        //指定reduce数量提高写数据的速度
        job.setNumReduceTasks(3);

        job.setJobName("HdfsToHbase");
        job.setJarByClass(Demo6HdfsToHbase.class);

        job.setMapperClass(HdfsToHbaseMap.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(NullWritable.class);

        TextInputFormat.addInputPath(job, new Path("/data/student"));


        /**
         * 指定reduce
         *
         * 指定表名
         *create 'stu','info'
         */

        TableMapReduceUtil.initTableReducerJob("stu1", HdfsToHbaseReduce.class, job);


        job.waitForCompletion(true);

        /**
         *
         * hadoop jar  包名  类名
         *
         */

    }
}
